package org.ccheng.xztx.service.impl;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ReUtil;
import io.reactivex.Observable;
import org.ccheng.xztx.domain.ContestInfo;
import org.ccheng.xztx.domain.ContestUser;
import org.ccheng.xztx.domain.UserInfo;
import org.ccheng.xztx.service.ContestService;
import org.ccheng.xztx.service.UserService;
import org.ccheng.xztx.util.Api;
import org.ccheng.xztx.util.ApiConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class ContestServiceImpl implements ContestService {

    @Autowired
    private UserService userService;

    public ContestInfo findRival() {
        ContestInfo info = Api.get(ApiConstants.API_CONTEST_REFRESH_RIVALS, null, ContestInfo.class);

        List<ContestUser> userList = info.getUserList();

        for (ContestUser user : userList) {
            user.setUserInfo(userService.findById(user.getUserId()));
        }

        return info;
    }

    public void auto() {
        ContestInfo contestInfo = findRival();
        // 获取自己的属性
        UserInfo userInfo = userService.findById(null);

        // 获取所有对手
        List<ContestUser> enemyList = contestInfo.getUserList();

        for (ContestUser user : enemyList) {
            Long myAtk = Long.parseLong(userInfo.getAttack());
            Long enemyAtk = Long.parseLong(user.getUserInfo().getAttack());

            if (myAtk > enemyAtk) {
                System.out.println("敌人[" +
                        user.getUserInfo().getUsername() +
                        "] (ID:" + user.getUserInfo().getId() +
                        ") 攻击力:" + user.getUserInfo().getAttack() +
                        " 试探一下看打不打得过");

                pk(user.getUserInfo().getId());
            } else {
                System.out.println("敌人[" +
                        user.getUserInfo().getUsername() +
                        "] (ID:" + user.getUserInfo().getId() +
                        ") 攻击力:" + user.getUserInfo().getAttack() +
                        " 打不过，溜了溜了");
            }
        }
    }

    public void pk(String otherId) {
        Map<String, Object> params = MapUtil.newHashMap();
        params.put("otherId", otherId);

        String response = Api.get(ApiConstants.API_CONTEST_PK, params);
        String result = ReUtil.get("(?<=<div class=\"gaps normal\">).{0,20}(?=<br/><)", response, 0);

        System.out.println("结果:" + result);
    }
}
